package com.government.web.controller.search;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.government.app.bo.KeywordSearchBO;
import com.government.app.bo.KeywordSearchDetailsBO;
import com.government.app.vo.KeywordSearchDetailsVO;
import com.government.app.vo.KeywordSearchVO;
import com.government.area.domain.ParkArea;
import com.government.article.bo.ArticlePolicyBO;
import com.government.article.domain.ArticlePolicy;
import com.government.article.service.IArticleInformationService;
import com.government.article.service.IArticlePolicyService;
import com.government.article.service.IArticleService;
import com.government.common.constant.HttpStatus;
import com.government.common.core.controller.BaseController;
import com.government.common.core.domain.AjaxResult;
import com.government.common.core.domain.entity.SysUser;
import com.government.common.core.domain.model.LoginUser;
import com.government.common.core.page.TableDataInfo;
import com.government.common.core.text.Convert;
import com.government.common.utils.ServletUtils;
import com.government.common.utils.StringUtils;
import com.government.company.service.ICompanyService;
import com.government.item.service.IExcelDetailService;
import com.government.member.domain.BrowsingHistory;
import com.government.member.service.BrowsingHistoryService;
import com.government.org.service.IOrgInfoService;
import com.government.system.domain.WebRoleAuth;
import com.government.system.domain.vo.WebAuthVo;
import com.government.system.service.WebRoleAuthService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.government.common.core.page.TableSupport.PAGE_NUM;
import static com.government.common.core.page.TableSupport.PAGE_SIZE;


/**
 * 关键字搜索Controller
 *
 * @author system
 * @date 2023-09-14
 */
@RestController
@RequestMapping("/keyword/search")
public class KeywordSearchController extends BaseController {
    @Autowired
    private IOrgInfoService orgInfoService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IArticleInformationService articleInformationService;

    @Autowired
    private IArticlePolicyService articlePolicyService;

    @Autowired
    private BrowsingHistoryService browsingHistoryService;

    @Autowired
    private IExcelDetailService excelDetailService;
    @Autowired
    private WebRoleAuthService webRoleAuthService;

    @Autowired
    private ICompanyService companyService;

    /**
     * 关键字搜索列表（分页）
     */
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody KeywordSearchBO bo) {


        if (StrUtil.isNotBlank(bo.getKeyword())) {
            bo.setKeyword(bo.getKeyword().replace("(", "（"));
            bo.setKeyword(bo.getKeyword().replace(")", "）"));
        }
        SysUser sysUser = getLoginUser().getUser();
        Date now = DateUtil.date();
        List<KeywordSearchVO> result = Lists.newArrayList();

        if (CollUtil.isNotEmpty(bo.getSearchDistrict())) {
            bo.setDistrict(bo.getSearchDistrict());
        }
        // 政策范围处理
        if (CollUtil.isNotEmpty(bo.getDistrict())) {
            parkAreaHandler(bo);
        }
        // 主管部门-其他 特殊处理
        if (CollUtil.isNotEmpty(bo.getOrgTypes())) {
            bo.setOtherOrg("0");
            if (bo.getOrgTypes().size() == 1 && bo.getOrgTypes().get(0).equals("25")) {
                bo.setOtherOrg("1");
            }
        }

        if ("1".equals(bo.getSearchType())) {
            // 搜索范围处理
            List<String> informationRange = bo.getInformationRange();
            List<String> searchRange = Lists.newArrayList();
            if (CollectionUtil.isNotEmpty(informationRange) && StrUtil.isNotBlank(bo.getKeyword())) {

                for (String range : informationRange) {
                    if ("1".equals(range)) {
                        searchRange.add("t2.title");
                    } else if ("2".equals(range)) {
                        searchRange.add("t1.proof");
                    } else if ("3".equals(range)) {
                        searchRange.add("t2.content");
                    } else if ("4".equals(range)) {
                        searchRange.add("t1.attachments");
                    }
                }

            } else {
                if (StrUtil.isNotBlank(bo.getKeyword())) {
                    searchRange.add("t2.title");

                }
            }
            bo.setSearchRange(searchRange);
            // 发布时间处理
            if (StringUtils.isNotBlank(bo.getPublishTime())) {
                if ("1".equals(bo.getPublishTime())) {
                    bo.setPublishStartTime(DateUtil.formatDate(DateUtil.offsetWeek(now, -1)));
                } else if ("2".equals(bo.getPublishTime())) {
                    bo.setPublishStartTime(DateUtil.formatDate(DateUtil.offsetMonth(now, -1)));
                } else if ("3".equals(bo.getPublishTime())) {
                    bo.setPublishStartTime(DateUtil.formatDate(DateUtil.offset(now, DateField.YEAR, -1)));
                }
                bo.setPublishEndTime(DateUtil.formatDate(now));
            }
            if (Objects.isNull(sysUser) || !SysUser.isAdmin(sysUser.getUserId())) {

                WebAuthVo webAuthVo = webRoleAuthService.getAuthContent();
                String sortTime = DateUtil.formatDate(DateUtil.offsetMonth(new Date(), -Integer.parseInt(webAuthVo.getIsm())));
                bo.setSortTime(sortTime);
            }
            result = articleInformationService.selectArticleInformationList(bo);
            return getDataTable(result);
//            }
        } else if ("2".equals(bo.getSearchType())) {

            List<String> policyRange = bo.getPolicyRange();
            List<String> searchRange = Lists.newArrayList();
            if (CollectionUtil.isNotEmpty(policyRange) && StrUtil.isNotBlank(bo.getKeyword())) {
                for (String range : policyRange) {
                    if ("1".equals(range)) {
                        searchRange.add("t1.name");
                    } else if ("2".equals(range)) {
                        searchRange.add("t1.former_name");
                    } else if ("3".equals(range)) {
                        searchRange.add("t1.intro");
                    }
                }

            } else {
                if (StrUtil.isNotBlank(bo.getKeyword())) {
                    searchRange.add("t1.name");
                }
            }
            bo.setSearchRange(searchRange);

            result = articlePolicyService.searchArticlePolicyList(bo);
            return getDataTable(result);
        } else if ("3".equals(bo.getSearchType())) {
            List<String> ranges = bo.getInformationRange();
            List<String> searchRange = Lists.newArrayList();
            if (CollectionUtil.isNotEmpty(ranges) && StrUtil.isNotBlank(bo.getKeyword())) {
                for (String range : ranges) {
                    if ("1".equals(range)) {
                        searchRange.add("t1.org_name");
                    } else if ("2".equals(range)) {
                        searchRange.add("t1.former_name");
                    }
                }

            } else {
                if (StrUtil.isNotBlank(bo.getKeyword())) {
                    searchRange.add("t1.org_name");
                }
            }
            bo.setSearchRange(searchRange);
            result = orgInfoService.selectOrgList(bo);
            return getDataTable(result);
        } else if ("4".equals(bo.getSearchType())) {
            List<String> ranges = bo.getInformationRange();
            List<String> searchRange = Lists.newArrayList();
            if (CollectionUtil.isNotEmpty(ranges) && StrUtil.isNotBlank(bo.getKeyword())) {
                for (String range : ranges) {
//                    if ("1".equals(range)) {
//                        searchRange.add("t1.incorporation");
//                    }
//                    else
                        if ("2".equals(range)) {
                        searchRange.add("t1.project");
                    } else if ("3".equals(range)) {
                        searchRange.add("t3.name");
                    }
                }

            } else {
//                if (StrUtil.isNotBlank(bo.getKeyword())) {
//                    searchRange.add("t1.incorporation");
//                }
            }
            bo.setSearchRange(searchRange);
            result = excelDetailService.searchExcelDetailList(bo);
            return getDataTable(result);
        }
        return getDataTable(result);
    }

    private void parkAreaHandler(KeywordSearchBO bo) {
        if (CollUtil.isNotEmpty(bo.getDistrict())) {
            List<Long> lastPark = Lists.newArrayList();

            if (bo.getDistrict().size() > 0) {
                Long park1 = Long.parseLong(bo.getDistrict().get(0));
                bo.setPark1(park1);
            }
            if (bo.getDistrict().size() > 1) {
                Long park2 = Long.parseLong(bo.getDistrict().get(1));
                bo.setPark2(park2);
                if (CollUtil.isEmpty(bo.getSearchDistrict())) {
                    lastPark.add(bo.getPark1());
                }
            }
            if (bo.getDistrict().size() > 2) {
                Long park3 = Long.parseLong(bo.getDistrict().get(2));
                bo.setPark3(park3);
                if (CollUtil.isEmpty(bo.getSearchDistrict())) {
                    lastPark.add(bo.getPark2());
                }
            }
            if (bo.getDistrict().size() > 3) {
                Long park4 = Long.parseLong(bo.getDistrict().get(3));
                bo.setPark4(park4);
                if (CollUtil.isEmpty(bo.getSearchDistrict())) {
                    lastPark.add(bo.getPark3());
                }
            }
            if (bo.getDistrict().size() > 4) {
                Long park5 = Long.parseLong(bo.getDistrict().get(4));
                bo.setPark5(park5);
                if (CollUtil.isEmpty(bo.getSearchDistrict())) {
                    lastPark.add(bo.getPark4());
                }
            }
            if (bo.getDistrict().size() > 5) {
                Long park6 = Long.parseLong(bo.getDistrict().get(5));
                bo.setPark6(park6);
                if (CollUtil.isEmpty(bo.getSearchDistrict())) {
                    lastPark.add(bo.getPark5());
                }
            }
            if (CollUtil.isNotEmpty(bo.getSearchDistrict())) {
                lastPark.add(Long.parseLong(bo.getSearchDistrict().get(bo.getSearchDistrict().size() - 1)));
            }
            bo.setLastPark(lastPark);
        }
    }

    /**
     * 关键字搜索详情
     */
    @GetMapping(value = "/detail/{id}")
    public AjaxResult getInfo(KeywordSearchDetailsBO bo) {

        LoginUser loginUser = getLoginUser();

        BrowsingHistory browsingHistory = new BrowsingHistory();
        KeywordSearchDetailsVO result = new KeywordSearchDetailsVO();
        if ("1".equals(bo.getSearchType())) {
            articleService.browseNumAdd(Long.parseLong(bo.getId()));
            result = articleInformationService.selectArticleInformationDetails(bo);
        } else if ("2".equals(bo.getSearchType())) {
            articleService.browseNumAdd(Long.parseLong(bo.getId()));
            result = articlePolicyService.selectArticlePolicyDetails(bo);
        } else if ("3".equals(bo.getSearchType())) {
            orgInfoService.browseNumAdd(Long.parseLong(bo.getId()));
            result = orgInfoService.selectOrgDetails(bo);
        } else if ("4".equals(bo.getSearchType())) {
            result = companyService.selectCompanyInfo(bo.getName());
        }

        if (!loginUser.isVisitor()) {
            SysUser user = loginUser.getUser();

            if (Objects.nonNull(user)) {
                if (Objects.nonNull(result)) {
                    browsingHistory.setTitle(result.getTitle());
                    browsingHistory.setSourceType(bo.getSearchType());
                    browsingHistory.setCreateTime(new Date());
                    browsingHistory.setSourceId(Long.parseLong(result.getId()));
                    browsingHistory.setUserId(user.getUserId());
                    browsingHistory.setCreateBy(String.valueOf(user.getUserId()));
                    browsingHistoryService.insertBrowsingHistory(browsingHistory);
                }
            }
        }

        return success(result);
    }

}
